package respository

import (
	"gitee.com/song-yao-shun/MQH/common"
	"gitee.com/song-yao-shun/MQH/dto"
	"gitee.com/song-yao-shun/MQH/model"
	"gitee.com/song-yao-shun/MQH/vo"
	"gorm.io/gorm"
	"log"
)

//定义接口和定义增删改查的方法
type INodeRepository interface {
	Create(node model.Node)
	Update(node model.Node)
	SelectById(Id int)
	SelectFullNodeById(Id int)
	DeleteById(Id int)
	List(nodeList vo.NodeList)
}

type NodeRepository struct {
	DB *gorm.DB
}

func (n NodeRepository) Create(node model.Node) (int, error){

	if err := n.DB.Create(&node).Error; err != nil {
		log.Printf("新增失败，错误信息为：%v",err)
		return 0, err
	}

	return node.ID, nil
}

func (n NodeRepository) Update(node model.Node) (*model.Node, error){

	if err := n.DB.Updates(&node).Error;err != nil {
		return nil, err
	}

	return &node,nil
}

func (n NodeRepository) SelectById(Id int) (node *model.Node,err error){

	if err := n.DB.Where("id = ?",Id).First(&node).Error; err != nil{
		return nil, err
	}

	return
}

func (n NodeRepository) SelectFullNodeById(Id int) *dto.FullNodeDto {

	n.DB = n.DB.Where("nodes.id = ?", Id)
	selectSql := "nodes.id,nodes.name,nodes.scene_id as scene_id," +
		"s.name as scene_name,nodes.fct_id as fct_id,f.name as fct_name," +
		"nodes.created_at,nodes.updated_at"
	joinsSql := "left join scenes as s on nodes.scene_id = s.id " +
		"left join fcts as f on nodes.fct_id = f.id"

	var fullNode dto.FullNodeDto

	n.DB.Model(&model.Node{}).Select(selectSql).Joins(joinsSql).Scan(&fullNode)

	return &fullNode
}

func (n NodeRepository) DeleteById(Id int) (rowsAffected int64) {

	rowsAffected = n.DB.Where("id = ?", Id).Delete(model.Node{}).RowsAffected
	if rowsAffected != 1 {
		log.Printf("数据删除失败，删除操作影响行数为：%v，删除的id为：%v",rowsAffected,Id)
	}

	return
}
func (n NodeRepository) List(nodeList vo.NodeList) (nodes []dto.FullNodeDto, total int64){
	// 条件查询
	if nodeList.ID > 0  {
		n.DB = n.DB.Where("nodes.id = ?", nodeList.ID)
	}
	if nodeList.Name != ""  {
		n.DB = n.DB.Where("nodes.name like ?", "%" + nodeList.Name + "%")
	}
	if nodeList.SceneId > 0  {
		n.DB = n.DB.Where("nodes.scene_id = ?", nodeList.SceneId)
	}
	if nodeList.FctId > 0  {
		n.DB = n.DB.Where("nodes.fct_id = ?", nodeList.FctId)
	}
	if nodeList.PageNum == 0  {
		nodeList.PageNum = 1
	}
	if nodeList.PageSize == 0  {
		nodeList.PageSize = 10
	}

	selectSql := "nodes.id,nodes.name,nodes.scene_id as scene_id," +
		"s.name as scene_name,nodes.fct_id as fct_id,f.name as fct_name," +
		"nodes.created_at,nodes.updated_at"
	joinsSql := "left join scenes as s on nodes.scene_id = s.id " +
		"left join fcts as f on nodes.fct_id = f.id"

	//总记录数
	n.DB.Model(&model.Node{}).Count(&total)

	n.DB.Model(&model.Node{}).Select(selectSql).
		Joins(joinsSql).
		Order("nodes.created_at desc").
		Offset((nodeList.PageNum -1) * nodeList.PageSize).
		Limit(nodeList.PageSize).Scan(&nodes)

	return
}

func NewNodeRepository() NodeRepository{
	db := common.GetDB()
	//db.AutoMigrate(model.Node{})

	return NodeRepository{DB: db}
}
